package cn.afactory.tygz.ui.sns.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.common.UserListType;
import cn.afactory.tygz.model.SnsUserInfo;
import cn.afactory.tygz.model.SnsUserInfoList;
import cn.afactory.tygz.ui.base.BaseFragment;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshListView;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.sns.UserProfileActivity;
import cn.afactory.tygz.ui.sns.adapter.UserListAdapter;
import cn.afactory.tygz.ui.sns.controller.SnsControler;

public class UserListFragment extends BaseFragment implements UserListAdapter.OnItemClickListener {
    private static final String TAG = UserListFragment.class.getSimpleName();
    private static final int PAGE_SIZE = 10;
    protected SnsControler mController;
    protected UserListAdapter mAdapter;

    private LayoutInflater minflater;
    protected int mPageIndex = 1;
    protected int mPageSize = 10;
    private long mTargetUserId = -1;
    private int mUserType = -1;
    private long mPostId;
    //用户列表
    protected List<SnsUserInfo> mList = new ArrayList<SnsUserInfo>();

    public UserListFragment(long targetUserId,int userType,long postId) {
        mTargetUserId = targetUserId;
        mUserType = userType;
        mPostId = postId;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mController = new SnsControler(mContext, mUIHandler, null);
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        this.minflater = inflater;
        View mlayout = inflater.inflate(R.layout.fragment_health_subject, null);
        initViews(mlayout);
        showTitleBar(false);
//        mController.loadCacheData();
        return mlayout;
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SnsControler.MSG_FANS_LOADED_OK:
                handleFansList((SnsUserInfoList)msg.obj);
                break;
            case SnsControler.MSG_FANS_LOADED_KO:
                if (mAdapter.getCount() == 0) {
                    hideErrorPage(-1);
                    showErrorPage(msg.arg1, new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            startLoadUserList(true);
                        }
                    });
                } else {
                    LocalUtils.showToast(mContext, (String)msg.obj);
                }
                break;
            case SnsControler.MSG_RELOAD_FANS:
                startLoadUserList(true);
                break;

            case SnsControler.MSG_FOLLOWED_FANS_LOADED_OK:
                handleFollowedFansList((SnsUserInfoList)msg.obj);
                break;
            case SnsControler.MSG_FOLLOWED_FANS_LOADED_KO:
                if (mAdapter.getCount() == 0) {
                    hideErrorPage(-1);
                    showErrorPage(msg.arg1, new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            startLoadUserList(true);
                        }
                    });
                } else {
                    LocalUtils.showToast(mContext, (String)msg.obj);
                }
                break;

            case SnsControler.MSG_GET_PRASIZE_LIST_OK:
                handlePrasizeList((SnsUserInfoList)msg.obj);
                break;
            case SnsControler.MSG_GET_PRASIZE_LIST_KO:
                if (mAdapter.getCount() == 0) {
                    hideErrorPage(-1);
                    showErrorPage(msg.arg1, new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            startLoadUserList(true);
                        }
                    });
                } else {
                    LocalUtils.showToast(mContext, (String)msg.obj);
                }
                break;
        }

        // 结束下拉刷新
        if (plistview.isRefreshing()) {
            plistview.onRefreshComplete();
        }
    }

    /**
     * 获取我关注的列表
     * @param t
     */
    private void handleFollowedFansList(SnsUserInfoList t){
        hideErrorPage(-1);
        if (t.value != null && t.value.size() >= 0) {
            try {
                mList.addAll(t.value);
                //是否显示置顶链接VIEW
                mAdapter.setData(mList);
                mPageIndex = (mList.size()/mPageSize) + 1;
                setListListener();

                if (plistview.isRefreshing()) {
                    plistview.onRefreshComplete();
                }
                if (t.value.size() < PAGE_SIZE) {
                    plistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                } else {
                    plistview.setMode(PullToRefreshBase.Mode.BOTH);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (mAdapter.getCount() == 0) {
                showNullPage(true);
            }
        }
    }

    /**
     * 获取我的粉丝列表
     * @param t
     */
    private void handleFansList(SnsUserInfoList t){
        hideErrorPage(-1);
        if (t.value != null && t.value.size() >= 0) {
            try {
                mList.addAll(t.value);
                //是否显示置顶链接VIEW
                mAdapter.setData(mList);
                mPageIndex = (mList.size()/mPageSize) + 1;
                setListListener();

                if (plistview.isRefreshing()) {
                    plistview.onRefreshComplete();
                }
                if (t.value.size() < PAGE_SIZE) {
                    plistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                } else {
                    plistview.setMode(PullToRefreshBase.Mode.BOTH);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (mAdapter.getCount() == 0) {
                showNullPage(true);
            }
        }
    }

    /**
     * 处理点赞列表
     * @param t
     */
    private void handlePrasizeList(SnsUserInfoList t){
        hideErrorPage(-1);
        if (t.value != null && t.value.size() >= 0) {
            try {
                mList.addAll(t.value);
                //是否显示置顶链接VIEW
                mAdapter.setData(mList);
                mPageIndex = (mList.size()/mPageSize) + 1;
                setListListener();

                if (plistview.isRefreshing()) {
                    plistview.onRefreshComplete();
                }
                if (t.value.size() < PAGE_SIZE) {
                    plistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                } else {
                    plistview.setMode(PullToRefreshBase.Mode.BOTH);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (mAdapter.getCount() == 0) {
                showNullPage(true);
            }
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        startLoadUserList(true);
    }

    /**
     * 初始化组件 views
     *
     * @param view
     */
    private void initViews(View view) {
        plistview = (PullToRefreshListView) view.findViewById(R.id.plv_subject);
        initListView();
    }

    /**
     * 加载listview数据
     */
    protected void startLoadUserList(boolean cleanData) {
        if (cleanData) {
            mPageIndex = 1;
            mList.clear();
        }
        if(mUserType == UserListType.PRASIZE_LIST) {
            mController.doGetPrasizeUserList(mPostId, mPageIndex, mPageSize);
        } else if(mUserType == UserListType.MY_FANS) {
            mController.doLoadFansUserList(SPUtils.getUid(getActivity()),mPageIndex,mPageSize);
        } else if(mUserType == UserListType.MY_IDOLS) {
            mController.doLoadFollowedUserList(SPUtils.getUid(getActivity()), mPageIndex, mPageSize);
        } else if (mUserType == UserListType.COMPANY_USER) {
            //加载公司中的用户列表
            mController.doGetCompanyUserList(mPostId,mPageIndex, mPageSize);
        } else if (mUserType == UserListType.TOPIC_ATTENTION_USER_LIST) {
            //加载关注话题的用户列表
            mController.doGetFocusTopicUserList(mPostId,mPageIndex, mPageSize);
        }
    }

    /**
     * 初始化list view
     */
    private void initListView() {
        mAdapter = new UserListAdapter(mContext,null);
        plistview.setAdapter(mAdapter);
        plistview.setMode(PullToRefreshBase.Mode.BOTH);
        setListListener();
        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadUserList(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadUserList(false);
            }
        });
    }

    protected void setListListener() {
        plistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                gotoUserPage(mList.get(position - 1));
            }
        });
        mAdapter.setOnItemClickListener(this);
    }
    //跳转到个人主页
    private void gotoUserPage(SnsUserInfo snsUserInfo){
        if(snsUserInfo == null || snsUserInfo.userId <= 0){
            return;
        }
        try{
            UserProfileActivity.gotoUserProfile(getActivity(),snsUserInfo.userId,snsUserInfo.nickName);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void OnAttentionClick(TextView v, SnsUserInfo snsUserInfo) {
        mController.doFollowUser(v,snsUserInfo);
    }

    @Override
    public void onCancelAttentionClick(TextView v, SnsUserInfo snsUserInfo) {
        mController.doUnFollowUser(v, snsUserInfo);
    }
}
